package com.beaven.imclient.presenter.user;

import com.beaven.imclient.R;
import com.beaven.imclient.data.FriendRepository;
import com.beaven.model.Factory;
import com.beaven.model.data.DataSource;
import com.beaven.model.data.helper.DbHelper;
import com.beaven.model.data.helper.SessionHelper;
import com.beaven.model.data.helper.UserHelper;
import com.beaven.model.model.api.RspModel;
import com.beaven.model.model.card.UserCard;
import com.beaven.model.model.db.Session;
import com.beaven.model.model.db.User;
import com.chad.library.adapter.base.entity.MultiItemEntity;
import java.util.List;
import java.util.concurrent.TimeUnit;
import rx.Subscriber;
import rx.functions.Action1;
import timber.log.Timber;

/**
 * author: Beaven
 * time: 2017/5/26 16:12
 */

public class UserPresenter extends FriendRepository
    implements UserContract.Presenter, DataSource.FailedCallBack {

  private UserContract.View view;

  public UserPresenter(UserContract.View view) {
    this.view = view;
  }

  @Override public void subscribe() {
    load();
    //过滤短时间内多次数据库更改引起的多次列表重复刷新
    sub.throttleLast(1000, TimeUnit.MILLISECONDS).subscribe(new Action1<List<MultiItemEntity>>() {
      @Override public void call(List<MultiItemEntity> entities) {
        Timber.e("RxJava订阅---");
        view.showData(entities);
      }
    });
  }

  @Override public void unSubscribe() {
    destroy();
  }

  @Override public void deleteUser(String userId) {
    UserHelper.deleteUser(userId).subscribe(new Subscriber<RspModel<UserCard>>() {
      @Override public void onCompleted() {

      }

      @Override public void onError(Throwable e) {
        view.showText(R.string.data_network_error);
      }

      @Override public void onNext(RspModel<UserCard> userCardRspModel) {
        if (userCardRspModel.isSuccess()) {
          DbHelper.instance().deleteModel(User.class, userCardRspModel.getResult().build());
          Session session = SessionHelper.findFromLocal(userCardRspModel.getResult().getId());
          if (session != null) {
            DbHelper.instance().deleteModel(Session.class, session);
          }
        } else {
          Factory.decodeRspCode(userCardRspModel, UserPresenter.this);
        }
      }
    });
  }

  @Override public void loadDataFail(int strRes) {
    view.showText(strRes);
  }

  @Override protected void showList(List<MultiItemEntity> entities) {
    Timber.e("-----------首次加载---------------");
    view.showData(entities);
  }
}
